# -*- coding: UTF-8 -*-
"""
@File    ：第三周-第三节-作业.py
@Author  ：Super
@Date    ：2021/1/3
@Desc    ：作用域与装饰器
"""
from time import time

variable = 6


def local_fun() -> None:
    """
    将局部变量变成全局变量
    """
    global variable  # 使用 global 关键字将局部变量变成全局变量
    variable = 66
    print(variable)


# local_fun()
# print(variable)


def enclosed_fun():
    """
    将局部变量变成自由变量
    """
    total = 0
    count = 0

    def fun(value):
        nonlocal total, count  # 使用 nonlocal 关键字将局部变量变成全局变量
        total += value
        count += 1
        return total / count

    return fun


# avg = enclosed_fun()
# print(avg(1))


# 输出函数执行时间装饰器
def time_deco(fun):
    def wrapper(*args, **kwargs):
        start_time = time()
        result = fun(*args, **kwargs)
        end_time = time()
        print(f"{fun.__name__} 执行时间：{format(end_time - start_time, '.2f')} 秒")
        return result

    return wrapper


def cache_deco(fun):
    """
    为斐波那契数列添加缓存
    """
    cache = {}

    def wrapper(*args):
        if args not in cache:
            cache[args] = fun(*args)
        return cache[args]

    return wrapper


@cache_deco
@time_deco
def f(n):
    """
    使用递归重构斐波那契数列
    """
    if n <= 1:
        return 1
    return f(n - 1) + f(n - 2)


print(f(10))
